package com.wisemoresystem.seal.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.ne.framework.data.util.ChkTools;

import com.wisemoresystem.seal.model.t_user;
import com.wisemoresystem.seal.util.json.JsonCookieTools;

public class SessionDistributed {

	/**
	 * 设置值
	 * 
	 * @param name
	 * @param obj
	 * @param resp
	 */
	public static void setAttribute(String name, Object obj,
			HttpServletResponse resp) {
		setAttribute(name, obj, resp, false);
	}

	public static void setAttribute(String name, Object obj,
			HttpServletResponse resp, boolean isMax) {
		resp.setHeader("P3P", "CP=CAO PSA OUR");
		String jsonStr = JsonCookieTools.objToJiaMiJson(obj);

		Cookie cookie = new Cookie(name, jsonStr);
		// cookie.setDomain("sxjincan.com");
		cookie.setPath("/");
		if (isMax) {
			cookie.setMaxAge(12 * 30 * 24 * 60 * 60);
		}

		resp.addCookie(cookie);
	}

	/**
	 * 根据 name 获取 对应的值
	 * 
	 * @param name
	 * @param req
	 * @return
	 */
	public static Object getAttribute(String name) {
		if (ChkTools.isNull(name)) {
			return null;
		}
		if (name.equals(SessionVal.login_user)) {
			return getAttribute(name, t_user.class);
		} else {
			return null;
		}
	}

	public static Object getAttribute(String name, Class<?> clazz) {
		Object obj = null;

		Cookie cookie = null;
		Cookie[] cookies = WebTools.getRequest().getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (name.equals(c.getName())) {
					cookie = c;
					break;
				}
			}
		}

		if (cookie != null) {
			String val = cookie.getValue();
			try {
				obj = JsonCookieTools.jsonToObj(val, clazz);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return obj;
	}

	/**
	 * 清空cookie
	 */
	public static void clearLogin(HttpServletResponse resp) {
		Cookie[] cookies = WebTools.getRequest().getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				c.setPath("/");
				// c.setDomain("sxjincan.com");
				c.setValue(null);
				c.setMaxAge(0);
				resp.addCookie(c);

			}
		}
	}

}
